<script setup lang="ts">
import { ref } from 'vue'
import * as XLSX from 'xlsx'
import { User } from '@element-plus/icons-vue';
import { ElTable } from 'element-plus'

const post = ref({
  pageSize: 10,
  pageNumber: 1,

  pageSizeVIP: 5,
  pageNumberVIP: 1
})
//列表查询条件
//状态选择
const stateSelect = ref(0)
const stateValue = [
    {
        value: 0,
        label: '全部状态',
    },
    {
        value: 1,
        label: '未使用',
    },
    {
        value: 2,
        label: '已过期',
    },
    {
        value: 3,
        label: '已使用',
    },
    {
        value: 4,
        label: '已作废',
    }
]
//类型选择
const putTypeValue = ref('user')
const putTypeSelect = [
    {
        value: 'user',
        label: '领取用户',
    },
    {
        value: 'cardID',
        label: '优惠券编号',
    }
]
//时间
const dateBetween = ref([])
//input输入框，用户编号/优惠券编号
const putValue31 = ref('')

//优惠券领取列表，属性
interface User {
    cardID: string
    nickName: string
    name: string
    tel: string
    getTime: string
    operateTime: string
    state: number
    imageUrl: string
}
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
    console.log(multipleSelection.value);

}
const checked = ref(false)
//优惠券领取列表，数据
const VIPtableData: User[] = [
    //state:0-未使用（未过期）；1-已使用；2-已过期；3-已作废
    {
        cardID: '40012341223',
        nickName: 'pigpig',
        name: 'Phoebe',
        tel: '18349349604',
        getTime: '2019/04/10 11:56:02',
        operateTime: '2019/04/10 10:51:16',
        imageUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        state: 0
    },
    {
        cardID: '40012341265',
        nickName: 'switch',
        name: 'Tom',
        tel: '18349349604',
        getTime: '2019/04/10 11:56:02',
        operateTime: '2019/04/10 10:51:16',
        imageUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        state: 1
    },
    {
        cardID: '40012341273',
        nickName: 'pigpig',
        name: 'Tom',
        tel: '18349349604',
        getTime: '2019/04/10 11:56:02',
        operateTime: '2019/04/10 10:51:16',
        imageUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        state: 2
    },
    {
        cardID: '40012341284',
        nickName: 'pigpig',
        name: 'Tom',
        tel: '18349349604',
        getTime: '2019/04/10 11:56:02',
        operateTime: '2019/04/10 10:51:16',
        imageUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        state: 3
    }
]
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

//优惠券总数和使用作废情况
const allNum = ref(300)
const useNum = ref(20)
const outNum = ref(10)


/* 优惠券导出  Start -------------------------*/
//优惠券列表数据导出选项
const getOut = ref('')
const getOutData = [
    {
        value: 1,
        label: '导出选中',
    },
    {
        value: 2,
        label: '导出所有',
    }
]
//优惠券列表数据导出 方法
const getOutFn = (value: number) => {
    switch (value) {
        case 1:
            exportExcel({
                json: multipleSelection.value,//数据
                name: '考试计划表',//表名
                titleArr: ['cardID', 'nickName', 'name', 'tel',
                    'getTime',
                    'operateTime',
                    'imageUrl',
                    'state'],//表头
                sheetName: 'sheet',//页签
            })

            break
        case 2:
            exportExcel({
                json: VIPtableData,//数据
                name: '考试计划表',//表名
                titleArr: ['cardID', 'nickName', 'name', 'tel',
                    'getTime',
                    'operateTime',
                    'imageUrl',
                    'state'],//表头
                sheetName: 'sheet',//页签
            })
            break
        default:
            break
    }
}
//优惠券列表数据导出 Excel插件
interface excelType {
    json: object[];
    name: string;
    titleArr: string[];
    sheetName: string;
}
//优惠券列表数据导出 Excel插件
const exportExcel = (params: excelType) => {
    const keyArray = [];
    let data = [];
    const getLength = function (obj: object) {
        let count = 0;
        for (const i in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, i)) {
                count++;
            }
        }
        return count;
    };
    for (const key1 in params.json) {
        if (Object.prototype.hasOwnProperty.call(params.json, key1)) {
            const element = (params.json as { [key: string]: any })[key1];
            const rowDataArray = [];
            for (const key2 in element) {
                if (Object.prototype.hasOwnProperty.call(element, key2)) {
                    const element2 = (element as { [key: string]: object })[key2];
                    rowDataArray.push(element2);
                    if (keyArray.length < getLength(element)) {
                        keyArray.push(key2);
                    }
                }
            }
            data.push(rowDataArray);
        }
    }
    data.splice(0, 0, keyArray as any, params.titleArr as any);
    console.log(data);
    let ws = XLSX.utils.aoa_to_sheet(data);
    let wb = XLSX.utils.book_new();
    // 隐藏英文字段表头
    const wsrows = [{ hidden: true }];
    /* 设置worksheet每列的最大宽度 */
    const colWidth = data.map((row) =>
        row.map((val) => {
            /* 先判断是否为null/undefined */
            if (val == null) {
                return {
                    wch: 20,
                };
            } else if (val.toString().charCodeAt(0) > 255) {
                /* 再判断是否为中文 */
                return {
                    wch: val.toString().length * 2,
                };
            } else {
                return {
                    wch: val.toString().length * 2,
                };
            }
        })
    );
    /* 以第一行为初始值 */
    const result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
        for (let j = 0; j < colWidth[i].length; j++) {
            if (result[j].wch < colWidth[i][j].wch) {
                result[j].wch = colWidth[i][j].wch;
            }
        }
    }
    ws['!cols'] = result;
    ws['!rows'] = wsrows; // ws - worksheet
    XLSX.utils.book_append_sheet(wb, ws, params.sheetName);
    /* generate file and send to client */
    XLSX.writeFile(wb, `${params.name}.xlsx`);
}
/* 优惠券导出  End ---------------------------*/


//接口
import { getList } from '@/api/YouHuiQuan/YouHuiQuan'
import axios from 'axios';
let json:{page?:number,limit?:number,nickname?:string,status?:number,couponId?:string,uid?:string}={};
 //startTime?:Date,endTime?:Date
if(post.value.pageNumber){
    json.page=post.value.pageNumber;
}
if(post.value.pageSize){
    json.limit=post.value.pageSize
}
if(putTypeValue.value === 'user'){
    json.nickname=putValue31.value
}
if(putTypeValue.value === 'cardID'){
    json.couponId=putValue31.value
}
if(stateSelect.value){
    json.status=stateSelect.value
}
// if(new Date(dateBetween.value[0])){
//     //json.startTime=new Date(dateBetween.value[0])
//     json.startTime=new Date('')
// }
// if(new Date(dateBetween.value[1])){
//     //json.endTime=new Date(dateBetween.value[1])
//     json.endTime=new Date('')
// }

//接口？
// let getListInfo = async () => {
//     let { data }: { [propsName: string]: any } = await getList(json)
//     if (data.code == 200) {
//         console.log(json);
//         VIPtableData.values=data.data
//     }
// }

function getListInfo(){
    axios({
        url:'/coupon/user/get/list',
        method:'get',
        params:json
    }).then((res)=>{
        console.log(res);
        
    })
}

//查询领取列表按钮
const findGetList=()=>{
    console.log('page:',post.value.pageNumber);
    console.log('limit:',post.value.pageSize);
    console.log('putTypeValue:',putTypeValue.value);
    console.log('nickname/couponId:',putValue31.value);
    console.log('status:',stateSelect.value);
    console.log('startTime:',new Date(dateBetween.value[0]));
    console.log('endTime:',new Date(dateBetween.value[1]));
    
    getListInfo()
}

//分页数据  -- 改变一页数据条数----改变页码
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
}

//重置
const reSet=()=>{
    stateSelect.value=0;
    dateBetween.value=[];
    putValue31.value='';
}

</script>

<template>
    <div class="cardGetList">
        <div class="board">
            <div class="header flexBetween">
                <div class="headerL flex">
                    <div>
                        <el-select v-model="stateSelect" class="stateSelect" placeholder="全部状态" style="width: 100px;">
                            <el-option v-for="item in stateValue" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <div class="block marginLeft">
                        <el-date-picker v-model="dateBetween" type="daterange" unlink-panels="true" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" />
                    </div>
                    <div class="marginLeft">
                        <el-input v-model="putValue31" placeholder="请输入搜索内容" class="input-with-select">
                            <template #prepend>
                                <el-select v-model="putTypeValue" class="stateSelect" placeholder="领取用户"
                                    style="width: 123px;">
                                    <el-option v-for="item in putTypeSelect" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </template>
                        </el-input>
                    </div>
                </div>
                <div class="headerR flexBetween">
                    <el-button type="primary" style="width: 45%;" class="find" @click="findGetList">查询</el-button>
                    <el-button style="width: 45%;" class="reSet" @click="reSet">重置</el-button>
                </div>
            </div>
            <div class="headerT flexBetween marginTop">
                <div class="headerTL"
                    style="height: 30px; line-height: 30px; padding: 0 10px; color: gray; background-color: #E6F7FF;">
                    共领取 {{ allNum }} 张优惠券，
                    其中已使用 {{ useNum }} 张，
                    未使用 {{ allNum - useNum - outNum }},
                    已作废 {{ outNum }} 张。
                </div>
                <div class="headerTR flex">
                    <el-button style="width: 45%;" class="outMore">批量作废</el-button>
                    <el-select v-model="getOut" class="getOut" placeholder="导出" style="width: 100px;">
                        <el-option v-for="item in getOutData" :key="item.value" :label="item.label"
                            @click="getOutFn(item.value)" :value="item.value" />
                    </el-select>
                </div>
            </div>
            <div class="VIPinfo">
                <div class="pushBody marginTop">
                    <el-table ref="multipleTableRef" :data="VIPtableData"
                        style="width: 100%; border-top: 1px solid #D5D5D5;" class="VIPtable marginTop"
                        :cell-style="{ textAlign: 'center', padding: '10px 0' }" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" />
                        <el-table-column label="用户信息" width="350">
                            <template #default="scope">
                                <div class="flex">
                                    <el-avatar :src="scope.row.imageUrl" />
                                    <div class="userINfo">
                                        <div class="nickName">{{ scope.row.nickName }}</div>
                                        <div class="name">{{ scope.row.name }}</div>
                                        <div class="tel">{{ scope.row.tel }}</div>
                                    </div>
                                </div>
                            </template>

                        </el-table-column>
                        <el-table-column property="cardID" label="优惠券编号" width="200">
                            <template #default="scope">
                                <div class="cardID">{{ scope.row.cardID }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column property="getTime" label="领取时间" width="200">
                            <template #default="scope">
                                <div class="getTime">{{ scope.row.getTime }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column property="operateTime" label="操作时间" width="200">
                            <template #default="scope">
                                <div class="getTime">{{ scope.row.operateTime }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column property="state" label="状态" show-overflow-tooltip>
                            <template #default="scope">
                                <div class="getTime">
                                    <label v-if="scope.row.state === 0">未使用</label>
                                    <label v-if="scope.row.state === 1">已使用</label>
                                    <label v-if="scope.row.state === 2">已过期</label>
                                    <label v-if="scope.row.state === 3">已作废</label>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="marginTop flexWC">
                        <el-pagination v-model:current-page="post.pageNumber" v-model:page-size="post.pageSize"
                            :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" :background="background"
                            layout="total, sizes, prev, pager, next, jumper" :total="400" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped lang="less">
@import url('./YouHuiQuan.css');

div {
    box-sizing: border-box;
}

.cardGetList {
    width: 100%;
    height: 100%;
    font-size: 10px;
    background-color: #F2F2F2;
    border-top: 1px #D5D5D5 solid;
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: center;

    .board {
        width: 95%;
        height: 92%;
        padding: 30px 1.5%;
        background-color: white;
        margin-top: 30px;
        font-size: 1.5em;


    }
}
</style>
